import React from 'react';
import { Upload, Icon, message } from 'antd';

function getBase64(img, callback) {
    const reader = new FileReader();
    // 文件读取成功完成时触发
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

/*const action = http://localhost:61110/upload;
const action = http://www.bestzsyl.cn:61110/upload;*/

function beforeUpload(file) {
    const TYPE = ['image/jpeg', 'image/png']
    if(!TYPE.includes(file.type)) {
        message.error('图片格式仅支持JPG、PNG');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小不能超过2MB!');
    }
    return TYPE.includes(file.type) && isLt2M;
}

class MyUpload extends React.Component {
    state = {
        loading: false,
    };

    handleChange = (info) => {
        console.log(info)
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, imageUrl => this.setState({
                imageUrl,
                loading: false,
            }));

            this.props.uploadChange(info.file.result.data)
        }
    }

     render() {
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">Upload</div>
            </div>
            );
            const imageUrl = this.state.imageUrl;
            return (
                <Upload
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="http://www.bestzsyl.cn:61110/upload"
                    beforeUpload={beforeUpload}
                    onChange={this.handleChange}
                >
                    {imageUrl ? <img src={imageUrl} alt="avatar" style={{width: 104, height: 104}} /> : uploadButton}
                </Upload>
        );
    }
}

export default MyUpload;